package com.sanjin.service.impl;

import com.sanjin.convert.ParkLotConvert;
import com.sanjin.entity.ParkLot;
import com.sanjin.exception.MyException;
import com.sanjin.form.ParkLotForm;
import com.sanjin.repository.ParkLotRepository;
import com.sanjin.service.ParkLotService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

/**
 * @description:
 * @author: sanjin
 * @date: 2019/5/5 14:14
 */
@Service
public class ParkLotServiceImpl implements ParkLotService {

    @Autowired
    private ParkLotRepository parkLotRepository;

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public ParkLot createParkLot(ParkLot parkLot) {
        if (parkLot.getId() != null)
            throw new MyException("id 必须为null");

        // status 默认设置为 0
        parkLot.setStatus(0);
        parkLotRepository.save(parkLot);
        return parkLot;
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public ParkLot updateParkLot(ParkLot parkLot) {
        if (parkLot.getId() == null)
            throw new MyException("id 不能为空");
        parkLotRepository.save(parkLot);
        return parkLot;
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void deleteByids(List<Integer> ids) {
        ids.forEach(id -> {
            parkLotRepository.deleteById(id);
        });
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public Page<ParkLot> queryParkLotByPage(PageRequest pageRequest) {
        Page<ParkLot> parkLots = parkLotRepository.findAll(pageRequest);
        return parkLots;
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public ParkLot queryParkLotById(Integer id) {
        Optional<ParkLot> optional = parkLotRepository.findById(id);
        return optional.orElse(null);
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public List<ParkLot> queryParkLots() {
        return parkLotRepository.findAll();
    }
}
